package jp.co.cyberagent.android.gpuvideo.filter;

import android.opengl.GLES11Ext;
import android.opengl.GLES20;

import java.nio.FloatBuffer;

import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter;

/**
 * @author wenjie
 */
public final class GPUVideoFilter extends GPUImageFilter {

    public static final String NO_FILTER_FRAGMENT_SHADER = "" +
            "#extension GL_OES_EGL_image_external : require\n" +
            "precision mediump float;\n" +
            "varying vec2 textureCoordinate;\n" +
            "uniform samplerExternalOES inputImageTexture;\n" +
            "void main() {\n" +
            "    gl_FragColor=texture2D(inputImageTexture, textureCoordinate);\n" +
            "}\n";

    public GPUVideoFilter() {
        super(NO_FILTER_VERTEX_SHADER, NO_FILTER_FRAGMENT_SHADER);
    }

    @Override
    public void onDraw(int textureId, FloatBuffer cubeBuffer, FloatBuffer textureBuffer) {
        GLES20.glUseProgram(this.getProgram());
        this.runPendingOnDrawTasks();
        if (this.isInitialized()) {
            cubeBuffer.position(0);
            GLES20.glVertexAttribPointer(this.getAttribPosition(), 2, 5126, false, 0, cubeBuffer);
            GLES20.glEnableVertexAttribArray(this.getAttribPosition());
            textureBuffer.position(0);
            GLES20.glVertexAttribPointer(this.getAttribTextureCoordinate(), 2, 5126, false, 0, textureBuffer);
            GLES20.glEnableVertexAttribArray(this.getAttribTextureCoordinate());
            if (textureId != -1) {
                GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
                GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
                GLES20.glUniform1i(this.getUniformTexture(), 0);
            }

            this.onDrawArraysPre();
            GLES20.glDrawArrays(5, 0, 4);
            GLES20.glDisableVertexAttribArray(this.getAttribPosition());
            GLES20.glDisableVertexAttribArray(this.getAttribTextureCoordinate());
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
        }
    }
}
